let express = require("express");
let dict = require("../classes/dictionaryWorker");
const valid = require("../classes/validate.js");

let api = express.Router();
let dictionary = new dict();

let validate = new valid();

api.get("/checkword", async function( req , res ,next){
    
    //解析 校验是否符合英语单词格式
    let word = req.query['word'];
    //需要校验单词不是空的字符串
    console.log(word);
    let keyword = validate.isEnglishWord( word ) ? 
        word.trim() : null;
        console.log("keyword: ", keyword );
    if( !keyword ){
        next( 
            {
                status: 400,
                code: 400001,
                msg: "查询内容不是英文单词"
            }
            );
        return ;
    }
    
    try{
            //查单词
            let result = await dictionary.searchWord( keyword );
            console.log("result: ",result, result[0]);
            if( result.length == 0 ){
                //没有查到
                next({
                    status: 200,
                    code: 204001,
                    msg: "词库中没有这个单词"
                });
                return ;
            }
            //校验
            // vaalidateKeyWord(keyword);
            res.statusCode = 200;
            res.send( JSON.stringify({
                code: 0,
                data: result[0]
            }) );
            //数据查询
            res.end();
    }catch(err){
        console.log(err);
    }
    

});

//错误处理
api.use(function( err , req , res , next){
    console.log("err: ", err);
    if( err ){
        res.statusCode= err.status;
        res.send( JSON.stringify({
            code: err.code,
            msg: err.msg
        }) );
        res.end();
    }else{
        next();
    }

    
});


module.exports = api;
